﻿<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>

      <!-- 树形表格 -->
      <el-table :data="catelist" border row-key="cat_id">
        <!-- 索引列 -->
        <el-table-column type="index" label="#">
          <template v-slot="scope">
            <span>{{ scope.row.index }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分类名称" prop="cat_name"></el-table-column>
        <el-table-column label="是否有效" prop="cat_deleted">
          <template v-slot="scope">
            <i class="el-icon-error" v-if="scope.row.cat_deleted"></i>
            <i class="el-icon-success" v-else></i>
          </template>
        </el-table-column>
        <el-table-column label="排序">
          <template v-slot="scope">
            <el-tag size="mini" effect="dark" v-if="scope.row.cat_level === 0"
              >一级</el-tag
            >
            <el-tag
              size="mini"
              effect="dark"
              type="success"
              v-else-if="scope.row.cat_level === 1"
              >二级</el-tag
            >
            <el-tag size="mini" effect="dark" type="warning" v-else
              >三级</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
    >
      <!-- 添加分类的表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <!-- 级联选择框的区域 -->
          <el-cascader
            v-model="cascaderValue"
            :options="parentCateList"
            :props="cascaderProps"
            @change="handleChange"
            clearable
          >
            <!-- <el-cascader
            expand-trigger="hover"
            :options="parentCateList"
            :props="cascaderProps"
            v-model="selectedKeys"
            @change="parentCateChanged"
            clearable
            change-on-select
          > -->
          </el-cascader>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 查询参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 分类列表数据
      catelist: [],
      // 总数据条数
      total: 0,
      addCateDialogVisible: false,
      addCateForm: {
        // 分类的名称
        cat_name: '',
        // 父级分类的Id
        cat_pid: 0,
        // 当前分类的等级
        cat_level: 0
      },
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 父级分类的数据列表
      parentCateList: [],
      cascaderValue: [],
      cascaderProps: {
        // 鼠标覆盖上去的时候，直接展开子菜单
        expandTrigger: 'hover',
        // 通过哪个属性实现的父子嵌套
        children: 'children',
        // 指定看到的数据项的名称
        label: 'cat_name',
        // 指定选中项对应的字段名称
        value: 'cat_id',
        // 允许选中任意节点
        checkStrictly: true
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取分类列表数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })

      if (res.meta.status !== 200)
        return this.$message.error('获取商品分类失败！')

      // 循环每个一级分类，为其添加自定义的 index 属性
      res.data.result.forEach((item, i) => {
        item.index = i + 1
      })

      this.catelist = res.data.result
      this.total = res.data.total
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    // 展示添加分类的对话框
    showAddCateDialog () {
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    // 获取父级分类的数据列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })

      if (res.meta.status !== 200)
        return this.$message.error('获取父级分类失败！')

      this.parentCateList = res.data
      console.log(this.parentCateList)
    },
    // 当 cascader 选中项变化，会出发这个函数
    onCascaderChange () {
      console.log(this.cascaderValue)
      if (this.cascaderValue.length > 0) {
        // 为父级分类的Id赋值
        this.addCateForm.cat_pid = this.cascaderValue[
          this.cascaderValue.length - 1
        ]
      } else {
        this.addCateForm.cat_pid = 0
      }
      // 为当前分类的等级赋值
      this.addCateForm.cat_level = this.cascaderValue.length
    },
    addNewCate () {
      this.$refs.addCateFormRules.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201)
          return this.$message.error('添加分类失败！')

        this.$message.success('添加分类成功！')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    // 重置添加分类的表单数据
    onAddcateDialogClose () {
      this.$refs.addCateFormRef.resetFields()
      this.cascaderValue = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    }
  }
}
</script>

<style lang="less" scoped>
.el-icon-error {
  color: red;
}
.el-icon-success {
  color: #61ad00;
}
.el-cascader {
  width: 100%;
}
</style>
